package com.shyroke.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.shyroke.common.CommonUtils;
import com.shyroke.common.DateUtils;
import com.shyroke.entity.Article;
import com.shyroke.entity.Email;
import com.shyroke.entity.EmailEnum;
import com.shyroke.entity.FansKey;
import com.shyroke.entity.FriendDtoKey;
import com.shyroke.entity.Label;
import com.shyroke.entity.Role;
import com.shyroke.entity.ShowUser;
import com.shyroke.entity.SpiderDataDto;
import com.shyroke.entity.User;
import com.shyroke.entity.UserInfo;
import com.shyroke.entity.UserRoleKey;
import com.shyroke.mapper.EmailMapper;
import com.shyroke.service.ArticleServiceI;
import com.shyroke.service.EmailServiceI;
import com.shyroke.service.FansServiceI;
import com.shyroke.service.FriendServiceI;
import com.shyroke.service.LabelServiceI;
import com.shyroke.service.UserInfoServiceI;
import com.shyroke.service.UserRoleServiceI;
import com.shyroke.service.UserServiceI;
import com.shyroke.spider.Sprider;

@Controller
@RequestMapping(value = "/userAction")
public class UserAction {

	@Autowired
	private LabelServiceI labelService;

	@Autowired
	private UserServiceI userService;

	@Autowired
	private ArticleServiceI articleService;

	@Autowired
	private UserInfoServiceI userInfoService;

	@Autowired
	private FansServiceI fansService;

	@Autowired
	private UserRoleServiceI userRoleService;
	
	@Autowired
	JavaMailSender mailSender;
	
	@Autowired
	private EmailServiceI emailServiceI;
	
	@Autowired
	private FriendServiceI friendService;

	/**
	 * 用户未登录跳转到首页
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView loginView(ModelAndView model) {

		/**
		 * 获取文章的标签集合
		 */
		List<Label> labelList = labelService.selectAll();

		model.addObject("labelList", labelList);
		model.setViewName("login");

		return model;
	}

	/**
	 * 判断用户登录
	 * 
	 * @param user
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, String> login(User user, HttpSession session) {
		Map<String, String> map = new HashMap<String, String>();
		Subject subject = SecurityUtils.getSubject();

		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(user.getUsername(), user.getPassword());

		try {
			subject.login(usernamePasswordToken);
		} catch (UnknownAccountException e1) {
			map.put("errMsg", e1.getMessage());
		} catch (IncorrectCredentialsException e2) {
			map.put("errMsg", e2.getMessage());
		} catch (LockedAccountException e3) {
			map.put("errMsg", e3.getMessage());
		}

		if (map.size() > 0) {
			// 说明有异常
		} else {
			// 说明登录成功
			map.put("msg", "登录成功");

			/**
			 * 判断登录用户的角色
			 */
			User user1 = userService.selectUserByUserNameAndPwd(user.getUsername(), user.getPassword());
			session.setAttribute("user", user1);
			session.setAttribute("login", "login");
			int userId = user1.getId();
			List<Role> roleList = userService.selectRolesByUserId(userId);

			for (Role role : roleList) {
				String roleName = role.getRole();

				if (roleName.equals("admin")) {
					// 说明登录用户是管理员角色
					map.put("role", "admin");
					return map;
				} else if (!roleName.equals("admin") && roleName.equals("user")) {
					// 说明登录用户是普通用户
					map.put("role", "user");
				}
			}

		}

		// System.out.println(map);
		return map;
	}

	/**
	 * 跳转到用户详细信息页面
	 * 
	 * @param model
	 * @param articleId
	 *            文章id
	 * @param user_id
	 *            用户id
	 * @return
	 */
	@RequestMapping(value = "/userDesc")
	public ModelAndView userDesc(ModelAndView model,
			@RequestParam(value = "articleId", required = false) Integer articleId,
			@RequestParam(value = "userId", required = false) Integer user_id) {
		User user = null;
		if (user_id != null) {
			// 根据用户id来查找某个用户
			user = userService.selectByUserId(user_id);
		} else {
			// 根据文章id来查找某个用户
			Article article = articleService.selectById(articleId);
			int userId = article.getUserid();
			user = userService.selectByUserId(userId);
		}

		model.addObject("user", user);
		UserInfo userInfo = userInfoService.selectByUserId(user.getId());
		model.addObject("userInfo", userInfo);
		List<FansKey> fansList = fansService.selectByUserId(user.getId());
		model.addObject("fansMount", fansList.size());
		List<FansKey> guanzuList = fansService.selectByFansId(user.getId());
		model.addObject("guanzhuMount", guanzuList.size());
		model.setViewName("user/othermain");
		return model;
	}

	/**
	 * 跳转到注册页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/registerView")
	public String registerView() {
		return "user/register";
	}

	/**
	 * 发送邮件
	 * @param email 邮箱地址
	 * @param session
	 * @param type 更换邮箱发送邮件的标记，如果该属性为空则说明是注册时候发送的。
	 * @return
	 */
	@RequestMapping(value = "/sendEmailCode")
	@ResponseBody
	public Map<String, Object> sendEmailCode(@RequestParam(value = "email", required = true) String email,
			HttpSession session,
			@RequestParam(value = "type", required = false) String type) {
		Map<String, Object> map = new HashMap<>();

		// 邮箱不能为空
		if (email == null || email.equals("")) {
			map.put("errMsg", "邮箱不能为空");
			return map;
		} else {
			// 邮箱必须是没有注册过的
			boolean isExit = userService.isExitEmail(email);

			if (isExit) {
				// 说明该邮箱已经被注册过
				map.put("errMsg", "邮箱已经被注册过了，请换一个邮箱");
				return map;
			}
		}

		try {
			final MimeMessage mimeMessage = this.mailSender.createMimeMessage();
			final MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
			message.setFrom("qweyhj@qq.com");
			message.setTo(email);
			if(type!=null && !type.equals("")) {
				//更换邮箱发送的验证码
				message.setSubject("更换邮箱的验证码");
			}else {
				message.setSubject("注册验证码");
			}
			
			
			int code = CommonUtils.getCode();
			session.setAttribute("code", code);
			message.setText("您的验证码为:" + code);
			this.mailSender.send(mimeMessage);

			map.put("msg", "发送验证码成功");
		} catch (Exception ex) {
			ex.printStackTrace();
			map.put("errMsg", "发送验证码成功");
		}

		return map;
	}

	/**
	 * 保存用户注册的信息
	 * 
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "/saveRegister")
	@ResponseBody
	public Map<String, Object> saveRegister(HttpSession session, User user, UserInfo userInfo,
			@RequestParam(value = "code", required = true) String code) {
		Map<String, Object> map = new HashMap<>();
		String sendCode = String.valueOf((Integer) session.getAttribute("code"));

		if (!code.equals(sendCode)) {
			// 验证码不正确
			map.put("errMsg", "验证码错误");
			return map;
		}

		// 保存登录用户信息
		userService.insert(user);
		User user1 = userService.selectUserByUserNameAndPwd(user.getUsername(), user.getPassword());
		userInfo.setUserid(user1.getId());
		userInfoService.insert(userInfo);

		map.put("msg", "注册成功");
		return map;
	}

	/**
	 * 关注好友
	 * 
	 * @param userId
	 *            被关注用户的id
	 * @return
	 */
	@RequestMapping(value = "/guanzhu")
	@ResponseBody
	public Map<String, Object> guanzhu(@RequestParam(value = "userId", required = true) Integer userId,
			HttpSession session) {
		Map<String, Object> map = new HashMap<>();
		User user = (User) session.getAttribute("user");
		if (userId == user.getId()) {
			map.put("errMsg", "不能关注自己");
			return map;
		}
		FansKey fans = new FansKey();
		fans.setUserid(userId);
		fans.setFansid(user.getId());
		try {
			fansService.insert(fans);
		} catch (Exception e) {
			map.put("errMsg", "您已经关注过该用户了！");
			return map;
		}

		map.put("msg", "关注成功");

		return map;
	}

	/**
	 * 跳转到个人信息页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/informationView")
	public String informationView() {
		return "user/information";
	}

	/**
	 * 跳转到个人信息页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/userInfoView")
	public ModelAndView userInfoView(ModelAndView model, HttpSession session) {
		User user = (User) session.getAttribute("user");

		UserInfo userInfo = userInfoService.selectByUserId(user.getId());

		model.addObject("userInfo", userInfo);
		model.addObject("user", user);
		model.setViewName("user/userInfo");
		return model;
	}
	
	/**
	 * 保存用户信息
	 * @param userInfo
	 * @param session
	 * @param type 如果该属性不为空，则说明管理员进行修改某个用户，否则为用户自己修改
	 * @param userId 如果type属性不为空，则该属性也不能为空，说明管理员要修改用户的id
	 * @return
	 */
	@RequestMapping(value="/saveupt")
	@ResponseBody
	public Map<String,Object> saveupt(UserInfo userInfo,User formUser,HttpSession session,
			@RequestParam(value="type",required=false)String type,
			@RequestParam(value="id",required=false)Integer id){
		Map<String,Object> map=new HashMap<>();
		User user=null;
		if(type!=null) {
			//管理员修改用户信息
			userService.update(formUser);
			UserInfo userInfo1=userInfoService.selectByUserId(id);
			userInfo.setId(userInfo1.getId());
			userInfo.setUserid(id);
			userInfoService.update(userInfo);
		}else {
			//用户自己修改
			user=(User)session.getAttribute("user");
			userInfo.setUserid(user.getId());
			if("管理员".equals(user.getName())) {
				map.put("type", "admin");
			}else if("普通用户".equals(user.getName())){
				map.put("type", "普通用户");
			}
			
			userInfoService.update(userInfo);
		}
		
		
		map.put("msg", "修改成功");
		return map;
	}

	/**
	 * 跳转到个人中心的安全验证页面
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/safeInfoView")
	public ModelAndView safeInfoView(ModelAndView model,HttpSession session) {
		
		User user=(User)session.getAttribute("user");
		UserInfo userInfo=userInfoService.selectByUserId(user.getId());
		
		model.addObject("userInfo", userInfo);
		model.addObject("user", user);
		model.setViewName("user/safeInfo");
		return model;
	}
	
	/**
	 * 保存用户修改的密码
	 * @param repassword 原密码
	 * @param session
	 * @param password 新的密码
	 * @return
	 */
	@RequestMapping(value="/pwdupt")
	@ResponseBody
	public Map<String,Object> safeupt(@RequestParam(value="repassword")String repassword,HttpSession session,
			@RequestParam(value="password")String password){
		Map<String,Object> map=new HashMap<>();
		User user=(User)session.getAttribute("user");
		
		boolean isPwd=userService.isPwdCorret(user.getId(),repassword);
		
		if(isPwd) {
			//说明原密码正确
			user.setPassword(password);
			userService.update(user);
			session.removeAttribute("user"); //移除session的用户信息
			map.put("msg", "修改成功，请重新登录");
		}else {
			map.put("errMsg", "原密码错误");
			return map;
		}
		
		
		return map;
	}
	
	/**
	 * 用户修改邮箱
	 * @param email 邮箱地址
	 * @param session
	 * @param code 验证码
	 * @return
	 */
	@RequestMapping(value="/emailupt")
	@ResponseBody
	public Map<String,Object> emailupt(@RequestParam(value="email",required=true)String email,HttpSession session,
			@RequestParam(value="code",required=true)String code){
		Map<String,Object> map=new HashMap<>();
		User user=(User)session.getAttribute("user");
		String SessionCode=session.getAttribute("code")+"";
		
		if(code.equals(SessionCode)) {
			//验证码正确
			UserInfo userInfo=userInfoService.selectByUserId(user.getId());
			userInfo.setEmail(email);
			userInfoService.update(userInfo);
			map.put("msg", "修改成功");
		}else {
			map.put("errMsg", "验证码错误");
			return map;
		}
		
		return map;
	}
	
	
	/**
	 * 跳转到显示所有普通用户的页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/showUserView")
	public ModelAndView showUserView(ModelAndView model) {
		model.setViewName("admin/userMain");
		return model;
	}
	
	/**
	 * 获取管理员的用户管理页面的数据网格所需要的数据
	 * @param username 用户名，用于按用户名搜索
	 * @param page 第几页，
	 * @param rows 每页显示几条数据
	 * @return
	 */
	@RequestMapping(value="/getUserDataGrid")
	@ResponseBody
	public Map<String,Object> getUserDataGrid(@RequestParam(value="username",required=false)String username,
			@RequestParam(value="page",required=false)Integer page,
			@RequestParam(value="rows",required=false)Integer rows){
		Map<String,Object> resultMap=new HashMap<>();
		//获取数据库中普通用户的数量
		int count=userService.selectCountByUser();
		
		List<Map<String,Object>> dataList=new ArrayList<>();
		List<User> userList = null;
		
		if(page!=0 && rows!=0) {
			//分页
			int beginIndex=0;
			int endIndex=rows;
			if(page==1) {
				beginIndex = 0;
			}else {
				beginIndex = 0+(page-1)*rows;
			}
			
			if(username != null && !username.equals("")) {
				//按用户查找
				userList=userService.selectByUserName(username,beginIndex,endIndex);
			}else {
				 userList=userService.selectAll(beginIndex,endIndex); //获取所有普通用户信息
			}
		}
		
		
		
		Map<String,Object> columnMap = null;
		for(User user:userList) {
			columnMap=new HashMap<>();
			columnMap.put("id", user.getId());
			columnMap.put("username", user.getUsername());
			columnMap.put("password", user.getPassword());
			columnMap.put("status", user.getState());
			dataList.add(columnMap);
		}
		resultMap.put("total", count);
		resultMap.put("rows", dataList);
		return resultMap;
	}
	
	/**
	 * 管理员查看某个用户
	 * @param model
	 * @param userId 用户id
	 * @return
	 */
	@RequestMapping(value="/userDescByAdmin")
	public ModelAndView userDescByAdmin(ModelAndView model,@RequestParam(value="userId",required=true)Integer userId) {
		
		User user=userService.selectByUserId(userId);
		UserInfo userInfo=userInfoService.selectByUserId(userId);
		
		
		model.addObject("user", user);
		model.addObject("userInfo", userInfo);
		model.setViewName("admin/userDesc");
		return model;
	}
	
	
	/**
	 * 删除用户
	 * @param userId 用户id
	 * @return
	 */
	@RequestMapping(value="/del")
	@ResponseBody
	public Map<String,Object> del(@RequestParam(value="userId",required=true)Integer userId){
		Map<String,Object> map=new HashMap<>();
		
		//删除user表
		userService.deleteByUserId(userId);
		
		//删除userInfo表
		userInfoService.deleteByUserId(userId);
		
		//删除user_role表
		UserRoleKey userRole=new UserRoleKey();
		userRole.setRoleId(2);  //2表示普通用户，管理员只能删除普通用户的信息
		userRole.setUserId(userId);
		userRoleService.deleteByUserRole(userRole);
		
		map.put("msg", "删除成功");
		
		return map;
	}
	
	/**
	 * 跳转到搜索页面
	 * @return
	 */
	@RequestMapping(value="/searchView")
	public String searchView() {
		return "user/search";
	}
	
	
	/**
	 * 跳转到搜索页面
	 * @param model
	 * @param type 搜索类型，我的图书馆文章/全站/用户搜索
	 * @param key 搜索内容
	 * @return
	 */
	@RequestMapping(value="/search")
	public ModelAndView search(ModelAndView model,@RequestParam(value="type",required=true)String type,
			@RequestParam(value="key",required=true)String key,HttpSession session) {
	
		User user=(User)session.getAttribute("user");
		if(type.equals("myLib")) {
			//搜索我的图书馆文章
			if(user==null) {
				//未登录，不能使用我的图书馆文章搜索
				model.setViewName("user/search_noLogin");
			}else {
				//登录过
				if(key==null || key.equals("")) {
					model.setViewName("article/showLabelArticle");
					return model;
				} 
				List<Article> articleList = articleService.selectMyLibBySearchTitleAndContent(key,user.getId());
				model.addObject("articleList", articleList);
				model.setViewName("article/showLabelArticle");
			}
		}else if(type.equals("localLib")) {
			//搜索全站文章
			if(key==null || key.equals("")) {
				model.setViewName("article/showLabelArticle");
				return model;
			}
			List<Article> articleList = articleService.selectBySearchTitleAndContent(key);
			model.addObject("articleList", articleList);
			model.setViewName("article/showLabelArticle");
			
		}else if(type.equals("friend")) {
			//搜索馆友
			if(user==null) {
				//未登录，不能使用我的图书馆文章搜索
				model.setViewName("user/search_noLogin");
			}else {
				if(key==null || key.equals("")) {
					model.setViewName("article/showLabelArticle");
					return model;
				}
				
				ShowUser showUser = null;
				UserInfo userInfo = null;
				List<ShowUser> showUserList=new ArrayList<>();
				List<User> userList = userService.selectByUserNameNoPage(key);
				
				for(User user1:userList) {
					showUser = new ShowUser();
					userInfo=userInfoService.selectByUserId(user1.getId());
					showUser.setJianjie(userInfo.getJianjie());
					showUser.setTouxiangPath(userInfo.getTouxiangPath());
					showUser.setUsername(user1.getUsername());
					showUser.setId(user1.getId());
					showUserList.add(showUser);
				}
				
				model.addObject("showUserList", showUserList);
				model.setViewName("tongxunlu/guanzhu");
			}
			
		}else if(type.equals("other")) {
			//站外搜索
			List<SpiderDataDto> spiderDataDtos =  new Sprider().getData(key);
			
			
			session.setAttribute("spiderDataDtos", spiderDataDtos);
			model.addObject("spiderDataDtos", spiderDataDtos);
			model.setViewName("article/zhanwai_search");
		}
		
		return model;
	}
	
	
	/**
	 * 
	 * @return
	 */
	@RequestMapping(value="/isShouCang")
	@ResponseBody
	public Map<String,Object> isShouCang(@RequestParam(value="url",required=true)String url,HttpSession session){
		Map<String,Object> resultMap = new HashMap<>();
		List<SpiderDataDto> dataDtos = (List)session.getAttribute("spiderDataDtos");
		List<SpiderDataDto> result = dataDtos.stream().filter(p->p.getUrl().equals(url)).collect(Collectors.toList());
		resultMap.put("title", result.get(0).getTitle());
		resultMap.put("msg", "成功");
		return resultMap;
	}
	
	
	/**
	 * 保存用户转载的文章
	 * @return
	 */
	@RequestMapping(value="saveShoucang")
	@ResponseBody
	public Map<String,Object> saveShoucang(Article article,HttpSession session,@RequestParam(value="url",required=true)String url){
		Map<String,Object> map=new HashMap<String,Object>();
		List<SpiderDataDto> dataDtos = (List)session.getAttribute("spiderDataDtos");
		dataDtos.stream().filter(p->p.getUrl().equals(url));
		article.setContent(dataDtos.get(0).getContent());
		articleService.shoucangByother(article, session);
		map.put("msg", "收藏成功");
		
		return map;
	}
	
	/**
	 * 用户注销
	 * @param session
	 * @return
	 */
	@RequestMapping(value="zhuxiao")
	@ResponseBody
	public Map<String,Object> zhuxiao(HttpSession session){
		Map<String,Object> resultMap = new HashMap<>();
		
		session.removeAttribute("user");
		session.removeAttribute("login");
		resultMap.put("msg", "注销成功");
		
		
		return resultMap;
	}
	
	
	/**
	 * 跳转到用户中心
	 * @return
	 */
	@RequestMapping(value="newsView")
	public String newsView() {
		return "user/newsMain";
	}
	
	
	/**
	 * 获取用户邮件中心的数据
	 * @param session
	 * @param page 
	 * @param rows
	 * @return
	 */
	@RequestMapping("getNewsData")
	@ResponseBody
	public Map<String,Object> getNewsData(HttpSession session,
			@RequestParam(value="page",required=false)Integer page,
			@RequestParam(value="rows",required=false)Integer rows){
		User currenUser = (User) session.getAttribute("user");
		Map<String,Object> resultMap = new HashMap<>();
		List<Email> emaiList = null;
		if(page==0 && rows==0) {
			//不分页
			emaiList = emailServiceI.selectAll(currenUser.getId());
		}else {
			//分页
			int beginIndex=0;
			int endIndex=rows;
			if(page==1) {
				beginIndex = 0;
			}else {
				beginIndex = 0+(page-1)*rows;
			}
			
			emaiList = emailServiceI.selectAllByPage(currenUser.getId(),beginIndex,endIndex);
		}
		
		
		
		List<Map<String,Object>> dataList = new ArrayList<>();
		Map<String,Object> columnMap ;
		User sendUser = null;
		for(Email email:emaiList) {
			sendUser = userService.selectByUserId(email.getSenduserid());
			columnMap = new HashMap<>();
//			columnMap.put("status", email.getStatus());
			String status = email.getStatus();
			if("0".equals(status)) {
				//未读
				columnMap.put("icon", "img/weidu.png");
			}else { //已读
				columnMap.put("icon", "img/yidu.png");
			}
			columnMap.put("id", email.getId());
			columnMap.put("sendUserName", sendUser.getUsername());
			columnMap.put("title", email.getTitle());
			columnMap.put("sendTime", email.getSendtime());
			columnMap.put("content", email.getContent());
			dataList.add(columnMap);
		}
		
		
		
		resultMap.put("total", emaiList.size());
		resultMap.put("rows", dataList);
		return resultMap;
	}
	
	/**
	 * 跳转到查看邮件详情的页面
	 * @param emailId
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping(value="lookEmailView")
	public ModelAndView lookEmailView(@RequestParam(value="emailId",required=true)Integer emailId,
			ModelAndView model,HttpSession session) {
		
		Email email =  emailServiceI.selectByID(emailId);
		User sendUser = userService.selectByUserId(email.getSenduserid());
		/*
		 * 将邮件内容的xx替换为当前用户的用户名
		 */
		String content = email.getContent();
		content = content.replaceAll("\\#\\(username\\)", sendUser.getUsername());
		email.setContent(content);
		
		/* 
		 * 判断邮件类型：管理员发送/添加好友
		 */
		String type = email.getType();
		 if(EmailEnum.FRIEND.equals(type)) {
			//该邮件为添加好友的邮件,启用“同意”按钮
			 model.addObject("marker", "marker");
		}
		 
		 /*
		  * 将邮件修改为已标记
		  */
		 if("0".equals(email.getStatus())) {
			 email.setStatus("1");
			 emailServiceI.update(email);
		 }
	
		 
		model.addObject("email", email);
		model.addObject("sendUserName", sendUser.getUsername());
		model.setViewName("user/newsDesc");
		return model;
	}
	
	
	/**
	 * 添加好友
	 * @param session
	 * @param sendUserId
	 * @return
	 */
	@RequestMapping(value="addFriend")
	@ResponseBody
	public Map<String,Object> addFriend(HttpSession session,
			@RequestParam(value="sendUserId",required=true)Integer sendUserId){
		Map<String,Object> resultMap = new HashMap<>();
		
		User  user = (User) session.getAttribute("user");
		
		if(sendUserId==-1) {
			//说明该邮件是管理员发送的，不能添加为好友
			resultMap.put("msg", "不能添加管理员为好友");
			return resultMap;
		}
		
		/**
		 * 是否已经添加过好友
		 */
		boolean isFriend = friendService.isFriend(user.getId(),sendUserId);
		if(isFriend) {
			//已经是是好友
			resultMap.put("msg", "已经是好友了，不能重复添加好友");
			return resultMap;
		}
		
		
		/**
		 * 保存双方的好友信息
		 */
		FriendDtoKey friend = new FriendDtoKey();
		friend.setUserid(user.getId());
		friend.setFrienduserid(sendUserId);
		
		FriendDtoKey friend2 = new FriendDtoKey();
		friend2.setFrienduserid(user.getId());
		friend2.setUserid(sendUserId);
		
		friendService.save(friend);
		friendService.save(friend2);
		
		resultMap.put("msg", "添加好友成功");
		
		return resultMap;
	}
	
	
	/**
	 * 发送好友请求的邮件
	 * @param sesson
	 * @param userId
	 * @return
	 */
	@RequestMapping(value="friendRequest")
	@ResponseBody
	public Map<String,Object> friendRequest(HttpSession session,
			@RequestParam(value="userId",required=true)Integer userId){
		
		User currenUser = (User) session.getAttribute("user");
		
		Map<String,Object> resultMap = new HashMap<>();
		
		if(currenUser==null) {
			resultMap.put("msg", "请先登录");
			return resultMap;
		}
		
		
		
		Email email = new Email();
		email.setReceiveuserid(userId);
		email.setSendtime(DateUtils.getFormatCurrenDate());
		email.setStatus("0");
		email.setTitle(EmailEnum.TITLE);
		email.setContent(EmailEnum.CONTENT);
		email.setType(EmailEnum.FRIEND);
		email.setSenduserid(currenUser.getId());
		
		/**
		 * 该用户是否发送过好友请求
		 */
		boolean isSend = emailServiceI.isSend(currenUser.getId(),userId,email.getType());
		if(isSend) {
			resultMap.put("msg", "已经发送过好友请求！");
			return resultMap;
		}
		
		emailServiceI.save(email);
		resultMap.put("msg", "发送成功");
		return resultMap;
		
	}
	
	
	/**
	 * 删除邮件ID
	 * @param id
	 * @return
	 */
	@RequestMapping(value="emailDel")
	@ResponseBody
	public Map<String,Object> emailDel(@RequestParam(value="idarr",required=true)Integer[] ids){
		Map<String,Object> resultMap = new HashMap<>(); 
		
		if(ids.length>0) {
			for(Integer id:ids) {
				emailServiceI.deleteById(id);
			}
			resultMap.put("msg", "删除成功!");
		}
		
		return resultMap;
	}
	
}
